package com.feng.zhihao.apigeteway.gateway.bean.impl.GENERATION_RULE;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.springframework.stereotype.Component;

import com.feng.zhihao.apigeteway.entity.InterfaceFieldGenerationRule;
import com.feng.zhihao.apigeteway.entity.InterfaceFieldInfo;
import com.feng.zhihao.apigeteway.exception.ExceptionMessage;
import com.feng.zhihao.apigeteway.exception.GetewayException;
import com.feng.zhihao.apigeteway.gateway.ReqContext;
import com.feng.zhihao.apigeteway.gateway.bean.GENERATION_RULE;

@Component("GENERATION_RULE_JS")
public class GENERATION_RULE_JS implements GENERATION_RULE {

	@Override
	public Object generationValue(InterfaceFieldInfo interfaceFieldInfo, InterfaceFieldGenerationRule rule, ReqContext reqContext) {
		ScriptEngineManager sem = new ScriptEngineManager();
		ScriptEngine se = sem.getEngineByName("js");
		try {
			se.eval(rule.getJs());
			Invocable inv2 = (Invocable) se;
			return inv2.invokeFunction("generationValue", reqContext);
		} catch (ScriptException e) {
			throw new GetewayException(e,ExceptionMessage.GENERATION_RULE_JS_EXCEPTION,interfaceFieldInfo.getInterfaceFieldName(),rule.getOgnl(),rule.getGenerationRuleId());
		} catch (NoSuchMethodException e) {
			throw new GetewayException(e,ExceptionMessage.GENERATION_RULE_JS_EXCEPTION,interfaceFieldInfo.getInterfaceFieldName(),rule.getOgnl(),rule.getGenerationRuleId());
		}
	}

}
